//调用方法
function build_loader(arr,callBack){
	if(!(arr instanceof Array)){
		callBack = arr;
	}
    loader('build',arr,callBack);
}
function src_loader(arr,callBack){
	if(!(arr instanceof Array)){
		callBack = arr;
	}
    loader('src',arr,callBack);
}

function scriptOnload(url,callBack){
    var script = document.createElement("script");
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callBack && callBack();
            }
        };
    }else {
        script.onload = function(){
            callBack && callBack();
       	};
    }
}

function createScript(JSON){
    var aRelust=[];
    for(var i in JSON){
        aRelust.push(JSON[i]);
    }
    return aRelust;
}

function loader(configItem,arr,callBack){
    // 1. 第一步插入config.js
    scriptOnload('libs/config.js',function (){
        // 2.第二步插入依赖库
        var aDept=eval('config.public_dept');
        var aSelectDept=eval('config.'+configItem+'.dept');
        var aSelectDeptArr=[]
		var aPlug=eval('config.'+configItem+'.plugin');
		
		for(var i=0;i<aSelectDept.length;i++)
		{	
			var aa=aDept[aSelectDept[i]]
			aSelectDeptArr.push(aa);
		}
		console.log(aSelectDeptArr)
		var script=createScript(aPlug);

		var o=aSelectDeptArr.length;
		var x=0;
		function a(x,cb){
			cb();
		}

		var w=function (x){
			scriptOnload(aSelectDeptArr[x],function (){
				x++;
				if(x==o){
					x=null;
					y=null;
					// 3.第三步插入插件
					scriptPlug();
					return;
				}
				a(x,function(){
					y(x);
				})
			})
		};
		var y=function (x){
			scriptOnload(aSelectDeptArr[x],function (){
				x++;
				if(x==o){
					x=null;
					y=null;
					// 3.第三步插入插件
					scriptPlug();
					return;
				}
				a(x,function(){
					w(x);
				})
			})
		};
		w(x);

		// 判断arr参数是什么
		function scriptPlug(){
			var oHead=document.getElementsByTagName("head")[0];
			if(arr instanceof Array){
				var aRelust=[];
				for(var i=0;i<arr.length;i++){
					var bbb=eval('config.'+configItem+'.'+arr[i]);
					aRelust.push(bbb)
				}
				for(var i=0;i<arr.length;i++){
					var aS = document.createElement("script");
					aS.src = aRelust[i];
					oHead.appendChild(aS);
				}
				if(callBack){
					$(function(){
						callBack();
					});
				}
			}else{
				scriptOnload(script[0],function(){

					for(var i=1;i<script.length;i++){
						var aS = document.createElement("script");
						aS.src = script[i];
						oHead.appendChild(aS);
					}
					if(callBack){
						$(function(){
							callBack();
						});
					}

				})
			}
		}
    })
}